<?php
if (!defined('ABSPATH')) { exit; }
?>

<div class="wrap">
    <h1>🛤️ 访问路径</h1>
    <p class="description">分析蜘蛛访问的页面路径，了解蜘蛛爬取行为和网站结构</p>
    
    <!-- 筛选器 -->
    <div class="filter-section">
        <div class="filter-card">
            <div class="filter-header">
                <h3>筛选条件</h3>
            </div>
            <div class="filter-content">
                <div class="filter-group">
                    <label for="path-period">时间范围：</label>
                    <select id="path-period">
                        <option value="today">今天</option>
                        <option value="yesterday">昨天</option>
                        <option value="week" class="premium-option" data-premium="true">最近7天 🔒</option>
                        <option value="month" class="premium-option" data-premium="true">最近30天 🔒</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="path-spider">蜘蛛类型：</label>
                    <select id="path-spider">
                        <option value="">所有蜘蛛</option>
                        <option value="Googlebot">Google</option>
                        <option value="Baiduspider">百度</option>
                        <option value="Bingbot">必应</option>
                        <option value="Sogou">搜狗</option>
                        <option value="360Spider">360</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="path-type">URL类型：</label>
                    <select id="path-type">
                        <option value="">所有类型</option>
                        <option value="home">首页</option>
                        <option value="post">文章</option>
                        <option value="page">页面</option>
                        <option value="category">分类</option>
                        <option value="tag">标签</option>
                        <option value="author">作者</option>
                        <option value="search">搜索</option>
                        <option value="feed">Feed</option>
                        <option value="sitemap">Sitemap</option>
                        <option value="api">API</option>
                        <option value="other">其他</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="path-status">状态码：</label>
                    <select id="path-status">
                        <option value="">所有状态</option>
                        <option value="200">200</option>
                        <option value="301">301</option>
                        <option value="302">302</option>
                        <option value="404">404</option>
                        <option value="500">500</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="path-search">搜索URL：</label>
                    <input type="text" id="path-search" placeholder="输入URL关键词" />
                </div>
                <div class="filter-group">
                    <button id="apply-path-filter" class="button button-primary">应用筛选</button>
                    <button id="reset-path-filter" class="button">重置</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 统计概览 -->
    <div class="stats-overview">
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-value" id="total-paths">-</div>
                <div class="stat-label">总访问路径</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">🔗</div>
            <div class="stat-content">
                <div class="stat-value" id="unique-paths">-</div>
                <div class="stat-label">唯一路径</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">🕷️</div>
            <div class="stat-content">
                <div class="stat-value" id="active-spiders">-</div>
                <div class="stat-label">活跃蜘蛛</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-content">
                <div class="stat-value" id="avg-response-time">-</div>
                <div class="stat-label">平均响应时间</div>
            </div>
        </div>
    </div>
    
    <!-- URL类型分布图 -->
    <div class="url-type-chart-section">
        <div class="section-header">
            <h2>📈 URL类型分布</h2>
            <div class="chart-controls">
                <button id="toggle-chart-view" class="button">切换视图</button>
            </div>
        </div>
        <div class="chart-container">
            <canvas id="url-type-chart" width="800" height="400"></canvas>
        </div>
    </div>
    
    <!-- 访问路径列表 -->
    <div class="paths-list-section">
        <div class="section-header">
            <h2>📋 访问路径列表</h2>
            <div class="list-controls">
                <select id="paths-per-page">
                    <option value="20">每页20条</option>
                    <option value="50">每页50条</option>
                    <option value="100">每页100条</option>
                </select>
                <button id="export-paths" class="button">导出数据</button>
            </div>
        </div>
        
        <div class="paths-table-container">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>URL</th>
                        <th>类型</th>
                        <th>蜘蛛</th>
                        <th>访问次数</th>
                        <th>占比</th>
                        <th>状态码</th>
                        <th>响应时间</th>
                        <th>最后访问</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="paths-list-body">
                    <tr><td colspan="9">加载中...</td></tr>
                </tbody>
            </table>
            
            <div class="pagination-container">
                <div id="paths-pagination"></div>
            </div>
        </div>
    </div>
</div>

<style>
.filter-section {
    margin-bottom: 30px;
}

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
}

.filter-header h3 {
    margin: 0 0 20px 0;
    color: #1d2327;
    font-size: 18px;
    font-weight: 600;
}

.filter-content {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
}

.filter-group label {
    font-size: 13px;
    font-weight: 600;
    color: #50575e;
    margin-bottom: 2px;
}

.filter-group select,
.filter-group input {
    padding: 12px 16px;
    border: 1px solid #8c8f94;
    border-radius: 6px;
    font-size: 14px;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
    background-color: #fff;
    min-height: 44px;
    flex: 1;
}

.filter-group select:focus,
.filter-group input:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 1px #007cba;
}

.filter-group select:hover,
.filter-group input:hover {
    border-color: #007cba;
}

.filter-group:last-child {
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: end;
    grid-column: 1 / -1;
    justify-content: flex-start;
    margin-top: 15px;
}

.filter-group:last-child button {
    margin: 0;
    min-width: 100px;
}

.stats-overview {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 1px solid #e1e5e9;
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    font-size: 32px;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f9fa;
    border-radius: 50%;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #0073aa;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 12px;
    color: #666;
}

.url-type-chart-section,
.paths-list-section {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e1e5e9;
}

.section-header h2 {
    margin: 0;
    color: #333;
    font-size: 18px;
}

.chart-container {
    position: relative;
    height: 400px;
}

.paths-table-container {
    overflow-x: auto;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.url-type-badge {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.type-home { background: #e3f2fd; color: #1976d2; }
.type-post { background: #e8f5e8; color: #388e3c; }
.type-page { background: #fff3e0; color: #f57c00; }
.type-category { background: #f3e5f5; color: #7b1fa2; }
.type-tag { background: #e0f2f1; color: #00695c; }
.type-author { background: #fce4ec; color: #c2185b; }
.type-search { background: #e1f5fe; color: #0277bd; }
.type-feed { background: #f1f8e9; color: #558b2f; }
.type-sitemap { background: #fff8e1; color: #f9a825; }
.type-api { background: #fafafa; color: #424242; }
.type-other { background: #eceff1; color: #546e7a; }

.status-code {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
}

.status-200 { background: #d4edda; color: #155724; }
.status-301, .status-302 { background: #fff3cd; color: #856404; }
.status-404 { background: #f8d7da; color: #721c24; }
.status-500 { background: #f5c6cb; color: #721c24; }

@media (max-width: 1200px) {
    .filter-content {
        grid-template-columns: repeat(4, 1fr);
        gap: 18px;
    }
}

@media (max-width: 960px) {
    .filter-content {
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
    }
    
    .filter-card {
        padding: 15px;
    }
}

@media (max-width: 800px) {
    .filter-content {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
    }
}

@media (max-width: 600px) {
    .filter-content {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .filter-group:last-child {
        flex-direction: row;
        grid-column: 1;
        margin-top: 15px;
    }
    
    .stats-overview {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
    }
    
    .section-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .filter-card {
        padding: 15px;
        border-radius: 8px;
    }
}

@media (max-width: 480px) {
    .filter-content {
        gap: 12px;
    }
    
    .filter-group label {
        font-size: 12px;
    }
    
    .filter-group select,
    .filter-group input {
        padding: 8px 10px;
        font-size: 13px;
    }
    
    .filter-group:last-child {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group:last-child button {
        width: 100%;
    }
    
    .stats-overview {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    
    .stat-card {
        padding: 15px;
    }
}
</style>

<script src="<?php echo plugins_url('assets/js/chart.min.js', dirname(__FILE__) . '/../wp-url-spider.php'); ?>"></script>

<script>
jQuery(document).ready(function($) {
    let currentPage = 1;
    let totalPages = 1;
    
    // 统一令牌失效处理
    function isTokenInvalidResponse(resp) {
        const msg = resp && resp.data && (resp.data.message || resp.data.error || '');
        return resp && resp.success === false && typeof msg === 'string' && msg.indexOf('访问令牌无效或已过期') !== -1;
    }
    function ensureTokenBanner(upgradeUrl) {
        if ($('.token-invalid-banner').length) return;
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        const $banner = $('<div class="token-invalid-banner premium-notice" style="margin:12px 0;">\
            <div class="premium-restriction">\
                <span class="premium-icon">🔒</span>\
                <span class="premium-text">访问令牌无效或已过期</span>\
                <a href="'+ url +'" class="premium-link">立即激活</a>\
            </div>\
        </div>');
        $('.wrap').first().prepend($banner);
    }
    function showListTokenMessage($tbody, colspan, upgradeUrl) {
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        var html = '';
        html += '<tr><td colspan="'+ colspan +'" class="premium-notice">';
        html += '<div class="premium-restriction">';
        html += '<span class="premium-icon">🔒</span>';
        html += '<span class="premium-text">访问令牌无效或已过期</span>';
        html += '<a href="' + url + '" class="premium-link">立即激活</a>';
        html += '</div>';
        html += '</td></tr>';
        $tbody.html(html);
    }
    function showChartTokenMessage(containerSelector, upgradeUrl) {
        const url = upgradeUrl || (window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#');
        const $container = $(containerSelector);
        $container.html('<div class="premium-restriction" style="height:280px;display:flex;align-items:center;justify-content:center;">\
            <span class="premium-icon">🔒</span>\
            <span class="premium-text">访问令牌无效或已过期</span>\
            <a href="'+ url +'" class="premium-link">立即激活</a>\
        </div>');
    }
    
    // 初始化
    loadPathStats();
    loadUrlTypeChart();
    loadPathsList();
    
    // 筛选器事件
    $('#apply-path-filter').on('click', function() {
        // 简化验证：直接检查全局激活状态
        const period = $('#path-period').val();
        if (period === 'week' || period === 'month') {
            if (!window.wpSpiderMonitor || !window.wpSpiderMonitor.subscription || !window.wpSpiderMonitor.subscription.is_premium) {
                // 显示激活提示
                const $selectedOption = $('#path-period').find('option:selected');
                if ($selectedOption.hasClass('premium-option')) {
                    alert('7天和30天数据查看需要激活PRO版本');
                    // 重置为今天
                    $('#path-period').val('today');
                    return;
                }
            }
        }
        
        currentPage = 1;
        loadPathStats();
        loadUrlTypeChart();
        loadPathsList();
    });
    
    $('#reset-path-filter').on('click', function() {
        $('#path-period').val('today');
        $('#path-spider').val('');
        $('#path-type').val('');
        $('#path-status').val('');
        $('#path-search').val('');
        currentPage = 1;
        loadPathStats();
        loadUrlTypeChart();
        loadPathsList();
    });
    
    // 分页事件
    $('#paths-per-page').on('change', function() {
        currentPage = 1;
        loadPathsList();
    });
    
    // 导出数据
    $('#export-paths').on('click', function() {
        exportPathsData();
    });
    
    function loadPathStats() {
        $.post(ajaxurl, {
            action: 'spider_get_path_stats',
            period: $('#path-period').val(),
            spider: $('#path-spider').val(),
            type: $('#path-type').val(),
            status: $('#path-status').val(),
            search: $('#path-search').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                const stats = response.data;
                $('#total-paths').text(stats.total_paths || 0);
                $('#unique-paths').text(stats.unique_paths || 0);
                $('#active-spiders').text(stats.active_spiders || 0);
                $('#avg-response-time').text((stats.avg_response_time || 0) + 'ms');
            } else if (isTokenInvalidResponse(response)) {
                ensureTokenBanner(response.data && response.data.upgrade_url);
                $('#total-paths').text('-');
                $('#unique-paths').text('-');
                $('#active-spiders').text('-');
                $('#avg-response-time').text('-');
            }
        });
    }
    
    function loadUrlTypeChart() {
        // 直接使用访问路径接口获取明细并在前端聚合，确保与筛选条件一致
        $.post(ajaxurl, {
            action: 'spider_get_access_paths',
            period: $('#path-period').val(),
            spider: $('#path-spider').val(),
            type: $('#path-type').val(),
            status: $('#path-status').val(),
            search: $('#path-search').val(),
            page: 1,
            per_page: 1000,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                // 兼容多种返回结构：直接数组 / {items: []} / {paths: []}
                let items = [];
                if (Array.isArray(response.data)) {
                    items = response.data;
                } else if (response.data && Array.isArray(response.data.items)) {
                    items = response.data.items;
                } else if (response.data && Array.isArray(response.data.paths)) {
                    // 后端返回的是访问路径明细，前端聚合为类型分布
                    const acc = {};
                    response.data.paths.forEach(function(p) {
                        const key = p.url_type || 'other';
                        const inc = parseInt(p.visit_count, 10) || 1;
                        acc[key] = (acc[key] || 0) + inc;
                    });
                    items = Object.keys(acc).map(function(k){ return { url_type: k, count: acc[k] }; });
                }
                console.log('URL类型统计数据(聚合后):', items);
                renderUrlTypeChart(items);
            } else if (isTokenInvalidResponse(response)) {
                ensureTokenBanner(response.data && response.data.upgrade_url);
                showChartTokenMessage('.url-type-chart-section .chart-container', response.data && response.data.upgrade_url);
            }
        });
    }
    
    function loadPathsList() {
        $('#paths-list-body').html('<tr><td colspan="9">加载中...</td></tr>');
        
        $.post(ajaxurl, {
            action: 'spider_get_access_paths',
            period: $('#path-period').val(),
            spider: $('#path-spider').val(),
            type: $('#path-type').val(),
            status: $('#path-status').val(),
            search: $('#path-search').val(),
            page: currentPage,
            per_page: $('#paths-per-page').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        }, function(response) {
            if (response.success) {
                const data = response.data;
                totalPages = data.total_pages || 1;
                
                let html = '';
                data.paths.forEach(function(path) {
                    html += '<tr>';
                    html += '<td>';
                    html += '<a href="' + path.url + '" target="_blank" title="' + path.url + '">';
                    html += path.url.length > 50 ? path.url.substring(0, 50) + '...' : path.url;
                    html += '</a>';
                    html += '</td>';
                    html += '<td><span class="url-type-badge type-' + path.url_type + '">' + path.url_type + '</span></td>';
                    html += '<td>' + path.spider_name + '</td>';
                    html += '<td>' + path.visit_count + '</td>';
                    html += '<td>' + path.percentage + '%</td>';
                    html += '<td><span class="status-code status-' + path.response_code + '">' + path.response_code + '</span></td>';
                    html += '<td>' + path.avg_response_time + 'ms</td>';
                    html += '<td>' + path.last_visit + '</td>';
                    html += '<td>';
                    html += '<button class="button button-small" onclick="viewPathDetails(\'' + path.url + '\')">详情</button>';
                    html += '</td>';
                    html += '</tr>';
                });
                $('#paths-list-body').html(html);
                
                // 更新分页
                updatePagination();
            } else {
                if (isTokenInvalidResponse(response)) {
                    ensureTokenBanner(response.data && response.data.upgrade_url);
                    showListTokenMessage($('#paths-list-body'), 9, response.data && response.data.upgrade_url);
                } else {
                    $('#paths-list-body').html('<tr><td colspan="9">加载失败</td></tr>');
                }
            }
        });
    }
    
    function updatePagination() {
        let paginationHtml = '';
        
        if (totalPages > 1) {
            // 上一页
            if (currentPage > 1) {
                paginationHtml += '<button class="button" onclick="goToPage(' + (currentPage - 1) + ')">‹ 上一页</button>';
            }
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                if (i === currentPage) {
                    paginationHtml += '<span class="button button-primary" style="margin: 0 2px;">' + i + '</span>';
                } else {
                    paginationHtml += '<button class="button" onclick="goToPage(' + i + ')" style="margin: 0 2px;">' + i + '</button>';
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                paginationHtml += '<button class="button" onclick="goToPage(' + (currentPage + 1) + ')">下一页 ›</button>';
            }
        }
        
        $('#paths-pagination').html(paginationHtml);
    }
    
    function showPremiumNotice(message) {
        const notification = $(`
            <div class="premium-notice" style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                border-radius: 8px;
                padding: 12px 16px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                border-left: 4px solid #ff6b6b;
                z-index: 9999;
                transform: translateX(100%);
                transition: transform 0.3s ease;
                max-width: 300px;
                font-size: 14px;
            ">
                <div class="premium-restriction">
                    <span class="premium-icon">🔒</span>
                    <span class="premium-text">${message}</span>
                    <a href="${window.wpSpiderMonitor ? wpSpiderMonitor.ajax_url.replace('admin-ajax.php', 'admin.php?page=spider-license') : '#'}" class="premium-link">立即激活</a>
                </div>
            </div>
        `);

        $('body').append(notification);
        
        // 显示动画
        setTimeout(() => notification.css('transform', 'translateX(0)'), 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.css('transform', 'translateX(100%)');
            setTimeout(() => notification.remove(), 300);
        }, 4000);
    }
    
    function renderUrlTypeChart(data) {
        const canvas = document.getElementById('url-type-chart');
        if (!canvas) {
            console.error('URL类型图表canvas未找到');
            return;
        }

        // 销毁现有图表
        if (window.urlTypeChart) {
            window.urlTypeChart.destroy();
        }

        try {
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取2D上下文');
                return;
            }

            // 处理数据
            const list = Array.isArray(data) ? data : [];
            const labels = list.map(item => item.url_type || item.label || '');
            const values = list.map(item => item.count || item.value || 0);
            
            // 定义颜色数组
            const colors = [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
                '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF',
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0'
            ];

            window.urlTypeChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: colors.slice(0, labels.length),
                        borderColor: '#ffffff',
                        borderWidth: 2,
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '50%'
                }
            });
        } catch (error) {
            console.error('渲染URL类型图表失败:', error);
        }
    }
    
    function exportPathsData() {
        const params = {
            action: 'spider_export_paths',
            period: $('#path-period').val(),
            spider: $('#path-spider').val(),
            type: $('#path-type').val(),
            status: $('#path-status').val(),
            search: $('#path-search').val(),
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        };
        
        const queryString = Object.keys(params).map(key => key + '=' + encodeURIComponent(params[key])).join('&');
        window.open(ajaxurl + '?' + queryString, '_blank');
    }
});

// 全局函数
function goToPage(page) {
    currentPage = page;
    loadPathsList();
}

function viewPathDetails(url) {
    // 打开URL详情页面或显示模态框
    window.open(url, '_blank');
}
</script>
